// <!--
//  * 严肃声明：
//  * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
//  * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
//  * Copyright (c) 2022 APThink David唐 all rights reserved.
//  * 版权所有，侵权必究！
//  *
// -->
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { i18n, loadLocaleMessages, setI18nLanguage } from '@/i18n'
import { toast, localDisableTip, saveLocalDisableTip, localLanguage, saveLocalLanguage, localTheme, saveLocalTheme, getToken, saveToken, removeToken } from '@/utils'
import { RoleMenuDefaultData, type MenuItem } from "@/contants";
import log from 'loglevel'

export const appStore = defineStore('app', () => {
  //菜单折叠状态
  const isMenuCollapse = ref(false)
  function toggleMenuCollapse() {
    isMenuCollapse.value = !isMenuCollapse.value;
  }
  
  const rolemenus = ref<Array<MenuItem>>(RoleMenuDefaultData);
   
  //当前选择语种
  const currentLanguage = ref(localLanguage())
  //当前ElementPlus语种
  const elementplusLocale = computed(() => {
    let locale = currentLanguage.value;
    if (locale === "zh") locale = "zhCn"
    return locale;
  })
  async function changeLanguage(data: string) {
    log.debug(currentLanguage.value + "=>" + data);
    saveLocalLanguage(data);
    currentLanguage.value = data;
    // load locale messages
    if (!i18n.global.availableLocales.includes(currentLanguage.value)) {
      await loadLocaleMessages(i18n, currentLanguage.value)
    }
    // set i18n language
    setI18nLanguage(i18n, currentLanguage.value)
  }

  const token = ref(getToken());
  const isLogin = computed(() => !!(token.value));
  function login(id: string) {
    log.debug(id);
    token.value = id;
    saveToken(id);
  }
  function logout() {
    log.debug(token.value);
    token.value = null
    removeToken()
    toast("成功退出系统")
  }

  const theme = ref(localTheme());
  function changeTheme(data: string) {
    log.debug(theme.value + "=>" + data);
    saveLocalTheme(data);
    theme.value = data;
  }

  const disableTip = ref(localDisableTip());
  function changeDisableTip(data: boolean) {
    log.debug(disableTip.value + "=>" + data);
    saveLocalDisableTip(data);
    disableTip.value = data;
  }

  return { disableTip, changeDisableTip, theme, changeTheme, rolemenus, isMenuCollapse, toggleMenuCollapse, currentLanguage, elementplusLocale, changeLanguage, isLogin, login, logout }
})
